package com.aiyige.page.my.order.myOrder;


import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.eventbus.EventBuySuccess;
import com.aiyige.base.eventbus.EventOrderChanged;
import com.aiyige.base.eventbus.EventOrderScreen;
import com.aiyige.base.eventbus.EventRefundAgree;
import com.aiyige.base.eventbus.EventRefundReject;
import com.aiyige.model.OrderEntity;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.request.OrderListForBuyerRequest;
import com.aiyige.model.response.OrderListResponse;
import com.aiyige.page.my.order.adapter.OrderListAdapter;
import com.aiyige.page.my.order.model.ScreenEntity;
import com.aiyige.page.my.order.model.SubjectSelection;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class MyOrdersDataPage extends BaseFragment implements CommonDataView.RetrofitStub {

    public static final int TYPE_All_PAGE_0 = 0;// 全部
    public static final int TYPE_WAITING_PAY_PAGE_1 = 1;// 待付款
    public static final int TYPE_WAITING_SERVICE_PAGE_2 = 2;// 待服务/发货
    public static final int TYPE_WAITING_AFFIRM_PAGE_3 = 3;// 待确认
    public static final int TYPE_AFTER_SALE_PAGE_4 = 4;// 退款/售后
    public static final int TYPE_CANCELLED_5 = 5;// 已取消

    private int pageType = -1;
    @BindView(R.id.cdv)
    CommonDataView cdv;

    OrderListAdapter adapter;

    ScreenEntity screenEntity;

    public MyOrdersDataPage() {
    }

    public String getPageTitle() {
        switch (pageType) {
            case TYPE_All_PAGE_0:
                return MyApp.getAppContext().getString(R.string.all);
            case TYPE_WAITING_PAY_PAGE_1:
                return MyApp.getAppContext().getString(R.string.waiting_pay_page);
            case TYPE_WAITING_SERVICE_PAGE_2:
                return MyApp.getAppContext().getString(R.string.waiting_service_page);
            case TYPE_WAITING_AFFIRM_PAGE_3:
                return MyApp.getAppContext().getString(R.string.waiting_affirm_page);
            case TYPE_AFTER_SALE_PAGE_4:
                return MyApp.getAppContext().getString(R.string.waiting_after_sale_page);
            case TYPE_CANCELLED_5:
                return MyApp.getAppContext().getString(R.string.order_status_cancel);
            default:
                return "";
        }
    }

    public int getPageType() {
        return pageType;
    }

    public void setPageType(int pageType) {
        this.pageType = pageType;
    }

    public static MyOrdersDataPage newInstance(int pageType) {
        MyOrdersDataPage fragment = new MyOrdersDataPage();
        fragment.setPageType(pageType);
        fragment.setAutoRegisterEventBus(true);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_order_manager_data, container, false);
        ButterKnife.bind(this, view);
        adapter = new OrderListAdapter();
        adapter.setHideTypeLayout(true);
        cdv.config(adapter, this);
        cdv.addItemDecoration(6, R.color.zwcolor_gray_f4f8f9);
        cdv.setRecyclerViewBgColor(ContextCompat.getColor(getActivity(), R.color.zwcolor_gray_f4f8f9));
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventOrderScreen(EventOrderScreen event) {
        screenEntity = event.screenEntity;
        cdv.refresh();
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventOrderDeleted(EventOrderDeleted event) {
//        if (adapter == null || adapter.getData() == null
//                || adapter.getData().isEmpty()
//                || event == null
//                || TextUtils.isEmpty(event.getId())) {
//            return;
//        }
//        List<OrderEntity> list = adapter.getData();
//        boolean find = false;
//        for (int i = 0; i < list.size(); i++) {
//            if (event.getId().equals(list.get(i).getOrderId())) {
//                list.remove(i);
//                find = true;
//                break;
//            }
//        }
//        if (find) {
//            adapter.notifyDataSetChanged();
//        }
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventOrderCancelled(EventOrderCancelled event) {
//        if (adapter == null || adapter.getData() == null
//                || adapter.getData().isEmpty()
//                || event == null
//                || TextUtils.isEmpty(event.getId())) {
//            return;
//        }
//        List<OrderEntity> list = adapter.getData();
//        boolean find = false;
//        for (int i = 0; i < list.size(); i++) {
//            if (event.getId().equals(list.get(i).getOrderId())) {
//                list.get(i).setStatus(OrderStatusEnum.STATUS_2_CANCEL.getStatus());
//                find = true;
//                break;
//            }
//        }
//        if (find) {
//            adapter.notifyDataSetChanged();
//        }
//        if (cdv != null && pageType == TYPE_CANCELLED_5) {
//            cdv.refresh();
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventOrderChanged(EventOrderChanged event) {
        if (adapter == null || adapter.getData() == null
                || adapter.getData().isEmpty()
                || event == null
                || TextUtils.isEmpty(event.getOrderEntity().getOrderId())) {
            return;
        }
        List<OrderEntity> list = adapter.getData();
        boolean find = false;
        for (int i = 0; i < list.size(); i++) {
            if (event.getOrderEntity().getOrderId().equals(list.get(i).getOrderId())) {
                list.remove(i);
                if (event.getOrderEntity().getStatus() != OrderEntity.STATUS_DELETED) {
                    list.add(i,event.getOrderEntity());
                }
                find = true;
                break;
            }
        }
        if (find) {
            adapter.notifyDataSetChanged();
        }
        if (cdv != null && pageType == TYPE_CANCELLED_5) {
            cdv.refresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccessEventBuss(EventBuySuccess eventBuySuccess) {
        if (cdv != null) {
            cdv.refresh();
        }
    }



    private List<String> getSubjects() {
        if (screenEntity != null && screenEntity.getTypes() != null
                && !screenEntity.getTypes().isEmpty()) {
            List<String> types = new ArrayList<>();
            for (SubjectSelection subjectSelection : screenEntity.getTypes()) {
                types.add(subjectSelection.getSubject());
            }
            return types;
        }
        return null;
    }

    private String getTime() {
        return screenEntity != null ? screenEntity.getTime() : "";
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {

        switch (pageType) {
            case TYPE_All_PAGE_0:
                return OrderListForBuyerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.ALL)
                        .timePeriod(getTime())
                        .build();
            case TYPE_WAITING_PAY_PAGE_1:
                return OrderListForBuyerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.NOPAY)
                        .build();
            case TYPE_WAITING_SERVICE_PAGE_2:
                return OrderListForBuyerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.NOSHIP)
                        .timePeriod(getTime())
                        .build();
            case TYPE_WAITING_AFFIRM_PAGE_3:
                return OrderListForBuyerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.UNCONFIRM)
                        .timePeriod(getTime())
                        .build();
            case TYPE_AFTER_SALE_PAGE_4:
                return OrderListForBuyerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.AFTERSALE)
                        .timePeriod(getTime())
                        .build();
            case TYPE_CANCELLED_5:
                return OrderListForBuyerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.CANCELLED)
                        .timePeriod(getTime())
                        .build();
            default:
                return OrderListForBuyerRequest.newBuilder()
                        .pageNum(currentPage)
                        .subject(getSubjects())
                        .uiStatus(Order.Range.ALL)
                        .timePeriod(getTime())
                        .build();
        }
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            OrderListResponse response = JSON.parseObject(respJson, OrderListResponse.class);
            if (response != null && !ListUtil.isEmpty(response.getContent())) {
                resultList.addAll(orderListToOrderEntityList(response.getContent()));
            }
            return new CommonDataView.HandleResult(response.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }

    }

    private List<OrderEntity> orderListToOrderEntityList(List<Order> list) {
        List<OrderEntity> orderEntityList = new ArrayList<>();
        if (!ListUtil.isEmpty(list)) {
            for (Order order : list) {
                orderEntityList.add(new OrderEntity(order));
            }
        }
        return orderEntityList;
    }

    @Override
    protected void initData() {
        cdv.doRefreshRequest();
    }
}
